const app = getApp()
let arr = []
const myRequest = require('../../assets/js/request.js');
const api = require('../../assets/js/api.js');
var WxParse = require('../../assets/js/wxParse/wxParse');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: ['https://oneplusminiapp-1300362285.cos.ap-shanghai.myqcloud.com/detail1.png', 'https://oneplusminiapp-1300362285.cos.ap-shanghai.myqcloud.com/detail2.png', 'https://oneplusminiapp-1300362285.cos.ap-shanghai.myqcloud.com/detail3.png', 'https://oneplusminiapp-1300362285.cos.ap-shanghai.myqcloud.com/detail4.png'],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    Hei: "",
    wid: "",
    chooseSize: false,
    animationData: {},
    activeIndex: '',
    detailslist: {},
    titlelist: [],
    typelist: [],
    choiceindex: 0, //选择分类的下标
    num: 1, //加入购物车时选择的商品数量
    shopsnum: 0, //购物车商品总数量
    carItem: {}, //加入购物车时显示的商品信息
    notice: false, //判断到货通知提示框，flase代表消失，true代表出现
    phone: '', //匹配手机号
  },
  changeIndicatorDots: function(e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function(e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function(e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function(e) {
    this.setData({
      duration: e.detail.value
    })
  },

  imgH: function(e) {
    var winWid = wx.getSystemInfoSync().windowWidth;
    var imgh = e.detail.height;
    var imgw = e.detail.width;
    var swiperH = winWid * imgh / imgw + "px"
    var swiperW = winWid
    this.setData({
      Hei: swiperH,
      wid: swiperW
    })
  },
  clickme: function() {
    this.setData({
      num: 1
    })
    this.showModal();
  },

  //点击去购物车
  gocar: function() {
    wx.switchTab({
      url: '/pages/scart/scart',
    })
  },
  //点击立即购买，跳转确认订单页
  goconfirmorder: function(e) {
    if (app.globalData.userInfo == null) {
      console.log(111)
      wx.showModal({
        title: '提示',
        content: '请先登录',
        confirmText: '确定',
        cancelText: '取消',
        success: function(res) {
          if (res.confirm) {
            wx.setStorage({
              key: 'isBack',
              data: 0,
            })
            wx.getStorage({
              key: 'accreditInfo',
              success: function (res) {
                wx.navigateTo({
                  url: '/pages/setting/setting',
                })
              },
              fail: function () {
                wx.switchTab({
                  url: '/pages/personal/personal',
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })
    } else {
      console.log(222)
      console.log(app.globalData.userInfo)
      let list = e.currentTarget.dataset
      let detail = e.currentTarget.dataset
      wx.navigateTo({
        url: '/pages/confirmorder/confirmorder?buynow=1&detail=' + JSON.stringify(detail),
      })
    }
  },
  //选择商品分类
  getreq: function(e) {
    arr = []
    this.setData({
      activeIndex: e.target.dataset.index,
      choiceindex: e.target.dataset.index
    })
  },

  //显示对话框
  showModal: function() {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 0)
  },
  //隐藏对话框
  hideModal: function() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 0)
  },

  //增加数量
  add: function() {
    let that = this
    if (that.data.num > 9) {
      that.data.num = 9
      wx.showToast({
        title: '限购10件',
        icon: 'none',
        mask: true
      })
    }
    this.setData({
      num: that.data.num + 1
    })
  },
  //减少数量
  reduce: function() {
    let that = this
    if (that.data.num < 2) {
      that.data.num = 2
    }
    this.setData({
      num: that.data.num - 1
    })
  },
  //填写数量
  writenum:function(e){
    console.log(e.detail.value)
    if (e.detail.value>10){
      this.setData({
        num: 10
      })
      wx.showToast({
        title: '限购10件',
        icon: 'none',
        mask: true
      })
    }else{
      this.setData({
        num: e.detail.value
      })
    }
  },

  //选择商品种类数量之后点击加入购物车
  addcart: function(e) {
    if (app.globalData.userInfo == null) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        confirmText: '确定',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {
            wx.setStorage({
              key: 'isBack',
              data: 0,
            })
            wx.getStorage({
              key: 'accreditInfo',
              success: function (res) {
                wx.navigateTo({
                  url: '/pages/setting/setting',
                })
              },
              fail: function () {
                wx.switchTab({
                  url: '/pages/personal/personal',
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })
    } 
    else{
      let list = e.currentTarget.dataset
      this.hideModal()
      //购物车图标右上角数量变化
      let that = this
      wx.getStorage({
        key: 'shopsnum',
        success: function (res) {
          res.data.push(that.data.num)
          wx.setStorage({
            key: 'shopsnum',
            data: res.data,
          })
          if (res.data.length == 0) {
            that.setData({
              shopsnum: 0
            })
          } else {
            that.setData({
              shopsnum: res.data.reduce((item, index) => {
                return item + index
              })
            })
          }
        },
      })
      //当前购买的商品明细添加入购物车列表的carlists本地存储中
      wx.getStorage({
        key: 'detailItem',
        success: function (res) {
          that.setData({
            carItem: {
              id: res.data.id,
              name: res.data.name,
              typename: res.data.typename,
              img: list.image,
              type: list.type,
              price: list.price,
              num: list.num,
              discount: list.discount,
              tz: list.tz
            }
          })
          console.log(that.data.carItem)
          wx.getStorage({
            key: 'carlists',
            success: function (res) {
              let flag = true
              res.data.forEach((item, index) => {
                if (item.id == that.data.carItem.id && item.type == that.data.carItem.type) {
                  flag = false
                  item.num = item.num + that.data.carItem.num
                }
              })
              if (flag == true) {
                res.data.push(that.data.carItem)
              }
              wx.setStorage({
                key: 'carlists',
                data: res.data,
              })
            },
          })
        },
      })
    }
  },

  //点击到货通知
  clickmeA: function() {
    console.log(111)
    this.setData({
      notice: true,
      phone:''
    })
  },
  //取消到货通知
  cancel: function() {
    this.setData({
      notice: false
    })
  },
  //确认到货通知信息
  sure: function() {
    let phonetel = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
    let that = this
    if (!phonetel.test(that.data.phone)) {
      wx.showToast({
        title: '手机号码格式不正确',
        icon: 'none',
        mask: true
      })
    } else {
      wx.showToast({
        title: '已登记,到货我们将第一时间通知您。',
        icon: 'none',
        mask: true
      })
      that.setData({
        notice: false,
      })
    }
  },
  //填写手机号
  writephone: function(event) {
    console.log(event.detail.value)
    this.setData({
      phone: event.detail.value
    })
  },

  //商品下架，返回首页
  sorryback: function() {
    wx.navigateBack({})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(app)
    let that = this
    wx.getStorage({
      key: 'detailItem',
      success: function(res) {
        console.log(res.data)
        that.setData({
          detailslist: res.data
        })
        console.log(that.data.detailslist.id)
        // let data = { 'id': that.data.detailslist.id }
        myRequest._post(api.richText).then((res) => {
          console.log(res)
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          WxParse.wxParse('article', 'html', res.data.richtext, that, 5);
        })
      },
    })
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          pixelRatio: res.pixelRatio,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      },
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    //页面显示时，都要先取一次shopsnum的本地存储赋给shopsnum
    wx.getStorage({
      key: 'shopsnum',
      success: function(res) {
        if (res.data.length == 0) {
          that.setData({
            shopsnum: 0
          })
        } else {
          that.setData({
            shopsnum: res.data.reduce((item, index) => {
              return item + index
            })
          })
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})